package io.gitee.kotle.android.utils


import io.gitee.kotle.android.BaseGlobalConst

/**
 * -------------------------------------腾讯替代sp的库-----------------------------------------
 */
private val kv
    get() = BaseGlobalConst.mmkv

/**
 * 移除key
 */
fun mmkvRemoveKey(keyName: String) = kv.removeValueForKey(keyName)

/**
 *  移除key
 */
fun mmkvRemoveKey(vararg keys: String) = kv.removeValuesForKeys(keys)

/**
 * 是否包含key
 */
fun mmkvContainsKey(keyName: String): Boolean = kv.containsKey(keyName)

/**
 * 保存数据
 */
fun mmkvPutValue(key: String, value: Any?) = kvEncode(key, value)

/**
 * 获取数据
 */
fun <T> mmkvGetValue(key: String, defaultValue: T) = kvDecode(key, defaultValue)

/**
 * 数据清除
 */
fun mmkvClearAll() = kv.clearAll()

/**
 * 数据清除
 */
fun mmkvClearMemoryCache() = kv.clearMemoryCache()

/**
 * 所有的key
 */
fun mmkvAllKeys() = kv.allKeys()

/**
 * 保存数据
 */
@Suppress("UNCHECKED_CAST")
fun kvEncode(keyName: String, keyValue: Any?): Boolean {
    if (keyValue == null) {
        if (mmkvContainsKey(keyName)) {
            mmkvRemoveKey(keyName)
        }
        return true
    }
    return when (keyValue) {
        is String -> {
            kv.encode(keyName, keyValue)
        }
        is Boolean -> {
            kv.encode(keyName, keyValue)
        }
        is Int -> {
            kv.encode(keyName, keyValue)
        }
        is Float -> {
            kv.encode(keyName, keyValue)
        }
        is Set<*> -> {
            kv.encode(keyName, keyValue as Set<String>)
        }
        is Long -> {
            kv.encode(keyName, keyValue)
        }
        is Double -> {
            kv.encode(keyName, keyValue)
        }
        is ByteArray -> {
            kv.encode(keyName, keyValue)
        }
        else -> {
            kv.encode(keyName, BaseGlobalConst.gson.toJson(keyValue))
        }
    }
}

/**
 * 解析数据
 */
@Suppress("UNCHECKED_CAST")
fun <T> kvDecode(keyName: String, default: T): T {
    if (!mmkvContainsKey(keyName)) {
        return default
    }
    @Suppress("IMPLICIT_CAST_TO_ANY")
    val result = when (default) {
        is String -> {
            kv.decodeString(keyName, default)
        }
        is Boolean -> {
            kv.decodeBool(keyName, default)
        }
        is Int -> {
            kv.decodeInt(keyName, default)
        }
        is Float -> {
            kv.decodeFloat(keyName, default)
        }
        is Set<*> -> {
            kv.decodeStringSet(keyName, default as Set<String>)
        }
        is Long -> {
            kv.decodeLong(keyName, default)
        }
        is Double -> {
            kv.decodeDouble(keyName, default)
        }
        is ByteArray -> {
            kv.decodeBytes(keyName, default)
        }
        else -> {
            val json = kv.decodeString(keyName, null)
            if (json == null) {
                default
            } else {
                BaseGlobalConst.gson.fromJson(json, default!!::class.java) ?: default
            }
        }
    }
    return result as T
}


